<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\VipOrderModel;
use App\Services\Logger;
use App\Services\PayServices;
use Illuminate\Support\Facades\DB;

class VipDao extends BaseDao
{

    public static function get_vip_order_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = VipOrderModel::query();

        $query->when(checkIsHasField($params,'order_code'),function ($query)use ($params){
            $query->where('order_code',$params['order_code']);
        });

        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        return $query;
    }

    /**
     * @param $params
     * @return array
     * @throws SysExceptions
     */
    public static function vip_pay($params = []): array
    {
        $userInfo = UsersDao::get_user_builder([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        if($userInfo['vip_level'] != 0){
            self::error('VIP等级不正确');
        }
        $inserData = [
            'order_code'=>makeOrderNo(),
            'price'=>399,
            'user_id'=>$params['user_id'],
        ];
        $result = self::get_vip_order_query()->create($inserData);
        if($result === false){
            self::error('下单失败');
        }
        return PayServices::pay([
            'order_code'=>$inserData['order_code'],
            'price'=>$inserData['price'],
            'openid'=>$userInfo['openid'],
            'notify_url'=>route('notice')
        ]);
    }

    public static function changeVip($order_code)
    {
        $orderInfo = self::get_vip_order_query([
            'order_code'=>$order_code,
            'status'=>0
        ]);
        if(!$orderInfo->exists()){
            Logger::info('++++.微信订单不存在');
            self::error('订单不存在');
        }
        $orderInfo = $orderInfo->first()->toArray();
        Logger::info("====>VIPxi修改",[
            'order_code'=>$order_code
        ]);
        DB::beginTransaction();
        //修改用户vip等级
        $res  = self::get_vip_order_query([
            'order_code'=>$order_code,
            'status'=>0
        ])->update([
            'status'=>1
        ]);
        $res !== false && $res = UsersDao::get_user_builder([
            'user_id'=>$orderInfo['user_id']
        ])->update([
            'vip_level'=>1
        ]);

        $userInfo = UsersDao::get_user_builder([
            'user_id'=>$orderInfo['user_id']
        ])->first()->toArray();
        //有上级
        if($userInfo['spread_id'] != 0){
            //查询有没有5个会员
            $user_count = UsersDao::get_user_builder([
                'spread_id'=>$userInfo['spread_id']
            ])->where('vip_level','<>',0)->count();


            $is_song = OrdersDao::get_order_child_builder([
                'user_id'=>$userInfo['spread_id']
            ])->where('is_song',1)->exists();
            //推广5个人并且没有赠送过
            if($user_count > 4 && !$is_song) {
                $value_pr = SettingsDao::get_settings_builder_query([
                    'key_name' => 'zengsong_project_id'
                ])->value('key_text');
                $projectInfo = ProjectDao::get_projects_builder([
                    'project_id' => $value_pr
                ]);
                if ($projectInfo->exists()) {
                    $projectInfo = $projectInfo->first()->toArray();
                    //赠送东西
                    $order_data = [
                        'user_id' => $userInfo['spread_id'],
                        'order_code' => makeOrderNo(),
                        'status' => 0
                    ];
                    $order_child_data = [
                        'user_id' => $userInfo['spread_id'],
                        'order_code' => $order_data['order_code'],
                        'json_data' => json_encode($projectInfo, JSON_UNESCAPED_UNICODE),
                        'project_id' => $value_pr,
                        'nums' => 1,
                        'price' => $projectInfo['project_price'],
                        'type' => 0,
                        'is_song' => 1
                    ];

                    $order_data['price'] = $order_child_data['price'];
                    $res !== false && $res = UsersDao::get_user_builder([
                        'user_id' => $userInfo['spread_id']
                    ])->update([
                        'is_tishi' => 1
                    ]);
                    $res !== false && $res = OrdersDao::get_order_builder()->create($order_data);
                    $res !== false && $res = OrdersDao::get_order_child_builder()->create($order_child_data);
                }
            }




            $user_spread_info = UsersDao::get_user_builder([
                'user_id'=>$userInfo['spread_id']
            ]);
            if($user_spread_info->exists()){
                $user_spread_info = $user_spread_info->first()->toArray();
                $vip_leve = $user_spread_info['vip_level'];
                if($user_spread_info['vip_level'] == 1){
                    $user_count = UsersDao::get_user_builder()
                        ->where('vip_level',1)
                        ->where('spread_id',$user_spread_info['user_id'])
                        ->count();
                    if($user_count >= 4){
                        $res !== false && $res= UsersDao::get_user_builder(['user_id'=>$user_spread_info['user_id']])->update([
                            'vip_level'=>2
                        ]);
                        $vip_leve = 2;
                    }
                }


                //无限向上
                if($vip_leve == 2){
                    $user_spread_id = $user_spread_info['spread_id'];
                    while (true){
                        if($user_spread_id == 0){
                            break;
                        }
                        $user_count_spread_all = UsersDao::get_user_builder([
                            'spread_id'=>$user_spread_id
                        ])->where('vip_level',2)
                        ->count();
                        if($user_count_spread_all >= 4){
                            $res !== false && $res = UsersDao::get_user_builder([
                                'user_id'=>$user_spread_id
                            ])->update([
                                'vip_level'=>3
                            ]);
                            $user_spread_id = UsersDao::get_user_builder([
                                'user_id'=>$user_spread_id
                            ])->value('spread_id');
                        }else{
                            break;
                        }

                    }
                }


//                $zhuamai_spread_query = UsersDao::get_shop_builder([
//                    'user_id'=>$user_spread_info['user_id']
//                ]);
//                if($zhuamai_spread_query->exists()){
//                    $res !== false && $res = UsersDao::get_user_builder([
//                        'user_id'=>$user_spread_info['user_id']
//                    ])->increment('money',399);
//                    $res !== false && $res = BillDao::get_bill_builder()->create([
//                        'user_id'=>$user_spread_info['user_id'],
//                        'num'=>399,
//                        'from_user_id'=>$orderInfo['user_id'],
//                        'pm'=>1,
//                        'type'=>1,
//                        'title'=>'购买会员奖励',
//                        'status'=>1
//                    ]);
//                }else{
//                    //如果是合伙人300
//                    if($user_spread_info['is_hehuo'] == 1){
//                        $res !== false && $res = UsersDao::get_user_builder([
//                            'user_id'=>$user_spread_info['user_id']
//                        ])->increment('money',300);
//                        $res !== false && $res = BillDao::get_bill_builder()->create([
//                            'user_id'=>$user_spread_info['user_id'],
//                            'from_user_id'=>$orderInfo['user_id'],
//                            'num'=>300,
//                            'pm'=>1,
//                            'type'=>1,
//                            'title'=>'购买会员奖励',
//                            'status'=>1
//                        ]);
//                        if($user_spread_info['spread_id'] != 0){
//                            $zhuamai_query = UsersDao::get_shop_builder([
//                                'user_id'=>$user_spread_info['spread_id']
//                            ]);
//                            if($zhuamai_query->exists()){
//                                $res !== false && $res = UsersDao::get_user_builder([
//                                    'user_id'=>$user_spread_info['spread_id']
//                                ])->increment('money',99);
//                                $res !== false && $res = BillDao::get_bill_builder()->create([
//                                    'user_id'=>$user_spread_info['spread_id'],
//                                    'num'=>99,
//                                    'from_user_id'=>$orderInfo['user_id'],
//                                    'pm'=>1,
//                                    'type'=>1,
//                                    'title'=>'购买会员奖励',
//                                    'status'=>1
//                                ]);
//                            }
//                        }
//                    }
//                }


            }
        }

        if($res === false){
            DB::rollBack();
            self::error('失败');
        }
        DB::commit();
        //返费
    }
}
